/*
 -----------------------------------------------------------------------------
 This source file is part of FolderProtector
 Copyright (c) 2011, Vyacheslav Chigrin, folderprotector (at) gmail.com  All rights reserved.
 Send your commends
	 ---The BSD 3-Clause License---
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation and/or
  other materials provided with the distribution.
* Neither the name of the Folder Protector project nor the names of its contributors
  may be used to endorse or promote products derived from this software without specific
  prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
  SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  -----------------------------------------------------------------------------
*/
#include "DriverController.h"
#include "CommonKMUM.h"
#include <assert.h>
#include <vector>
#include <iterator>
#include <wx/log.h>

CDriverController::CDriverController()
    : m_bHidingEnabled(false)
    , m_hParametersKey(NULL)
    , m_hServiceDevice(NULL)
{
}

CDriverController::~CDriverController()
{
    if(m_hParametersKey)
        RegCloseKey(m_hParametersKey);
    if(m_hServiceDevice!=NULL && m_hServiceDevice!=INVALID_HANDLE_VALUE)
        CloseHandle(m_hServiceDevice);
}
//returns true if communication with driver successfully established, false otherwise
bool CDriverController::Initialize()
{
    std::wstring parametersKey=L"System\\CurrentControlSet\\Services\\";
    parametersKey+=SERVICE_NAME;
    parametersKey+=L"\\Parameters";
    LONG status=RegOpenKeyExW(HKEY_LOCAL_MACHINE,parametersKey.c_str(),0,KEY_READ|KEY_WRITE,&m_hParametersKey);
    m_FilePaths.clear();
    if(m_hParametersKey==NULL || status!=ERROR_SUCCESS)
        return false;
    DWORD dwEnabled=0;
    DWORD dwType=0,dwSize=sizeof(dwEnabled);
    status=RegQueryValueEx(m_hParametersKey,HIDING_ENABLED_VALUE,NULL,&dwType,(BYTE*)&dwEnabled,&dwSize);
    if(dwType!=REG_DWORD || status!=ERROR_SUCCESS)
        return false;
    m_bHidingEnabled=(dwEnabled!=0);
    dwType=0;
    RegQueryValueEx(m_hParametersKey,HIDDEN_PATHS_VALUE,NULL,&dwType,NULL,&dwSize);
    if(dwType!=REG_MULTI_SZ || dwSize==0)
        return false;
    std::vector<BYTE> btBuf;
    btBuf.resize(dwSize);
    status=RegQueryValueEx(m_hParametersKey,HIDDEN_PATHS_VALUE,NULL,&dwType,&btBuf[0],&dwSize);
    if(status!=ERROR_SUCCESS)
        return false;
    wchar_t* p=(wchar_t*)&btBuf[0];
    while(*p)
    {
        std::wstring path=p;
        p+=path.length()+1;
        m_FilePaths.push_back(path);
    }
    if(!EnsureDriverIsRunning())
        return false;
    m_hServiceDevice=CreateFile(L"\\\\.\\"CONTROL_DEVICE_NAME,
        GENERIC_READ|GENERIC_WRITE,
        FILE_SHARE_READ,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL);
    if(m_hServiceDevice==INVALID_HANDLE_VALUE)
    {
        char szBuf[100];
        sprintf(szBuf,"ERROR %d",GetLastError());
        OutputDebugStringA(szBuf);
        return false;
    }
    return true;
}

const std::list<std::wstring>& CDriverController::GetFilePaths()const
{
    return m_FilePaths;
}

bool CDriverController::GetHidingEnabled()const
{
    return m_bHidingEnabled;
}

void CDriverController::SetHidingEnabled(bool enabled)
{
    m_bHidingEnabled=enabled;
    DWORD dwEnabled=enabled?1:0;
    RegSetValueEx(m_hParametersKey,HIDING_ENABLED_VALUE,0,REG_DWORD,(BYTE*)&dwEnabled,sizeof(dwEnabled));
    DWORD dwRet=0;
    DeviceIoControl(m_hServiceDevice,IOCTL_ENABLE_HIDING,&dwEnabled,sizeof(dwEnabled),NULL,0,&dwRet,NULL);
}

void CDriverController::AddHiddenPath(const std::wstring& path)
{
    m_FilePaths.push_back(path);
}

void CDriverController::RemoveHiddenPath(int index)
{
    std::list<std::wstring>::iterator it;
    it=m_FilePaths.begin();
    while(index>0 && it!=m_FilePaths.end())
    {
        it++;
        index--;
    }
    //index out of range?
    assert(it!=m_FilePaths.end());
    if(it!=m_FilePaths.end())
        m_FilePaths.erase(it);
}

void CDriverController::ApplyPathChanges()
{
    DWORD dwEnabled=m_bHidingEnabled?1:0;
    RegSetValueEx(m_hParametersKey,HIDING_ENABLED_VALUE,0,REG_DWORD,(BYTE*)&dwEnabled,sizeof(dwEnabled));
    DWORD dwPathsSize=0;
    std::list<std::wstring>::iterator it;
    std::vector<BYTE> vtBuf;
    for(it=m_FilePaths.begin();it!=m_FilePaths.end();it++)
        dwPathsSize+=(it->length()+1)*sizeof(wchar_t);
    dwPathsSize+=sizeof(wchar_t);
    vtBuf.reserve(dwPathsSize);
    for(it=m_FilePaths.begin();it!=m_FilePaths.end();it++)
    {
        std::wstring path=*it;
        const BYTE* pStart=(const BYTE*)path.c_str();
        std::copy(pStart,pStart+(path.length()+1)*sizeof(wchar_t),std::back_inserter(vtBuf));
    }
    //final terminator
    vtBuf.push_back(0);
    vtBuf.push_back(0);
    RegSetValueEx(m_hParametersKey,HIDDEN_PATHS_VALUE,0,REG_MULTI_SZ,&vtBuf[0],vtBuf.size());
    DWORD dwRet=0;
    DeviceIoControl(m_hServiceDevice,IOCTL_RELOAD_CONFIG,NULL,0,NULL,0,&dwRet,NULL);
}

bool CDriverController::EnsureDriverIsRunning()
{
    SC_HANDLE hSCM,hService;
    hSCM=OpenSCManager(NULL,NULL,SC_MANAGER_ENUMERATE_SERVICE);
    bool result=false;
    do
    {
        if(!hSCM)
            break;
        hService=OpenService(hSCM,SERVICE_NAME,SERVICE_QUERY_STATUS|SERVICE_START);
        if(!hService)
            break;
        SERVICE_STATUS status;
        memset(&status,0,sizeof(status));
        QueryServiceStatus(hService,&status);
        if(status.dwCurrentState==SERVICE_RUNNING)
        {
            result=true;
            break;
        }
        if(!StartService(hService,0,NULL))
            break;
        //3 sec. wait max
        for(int i=0;i<30;i++)
        {
            QueryServiceStatus(hService,&status);
            if(status.dwCurrentState==SERVICE_RUNNING)
            {
                result=true;
                break;
            }
            Sleep(100);
        }
    }while(0);
    if(hService)
        CloseServiceHandle(hService);
    if(hSCM)
        CloseServiceHandle(hSCM);
    return result;
}
